﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using YiSha.Util;
using YiSha.Util.Extension;
using YiSha.Util.Model;
using YiSha.Entity.SaleManage;
using YiSha.Model.Param.SaleManage;
using YiSha.Service.SaleManage;
using YiSha.Entity.SystemManage;
using YiSha.Business.Cache;
using YiSha.Model.Result.SystemManage;

namespace YiSha.Business.SaleManage
{
    /// <summary>
    /// 创 建：admin
    /// 日 期：2019-12-14 10:14
    /// 描 述：销售漏斗业务类
    /// </summary>
    public class FunnelBLL
    {
        private FunnelService funnelService = new FunnelService();
        private AreaCache areaCache = new AreaCache();
        private ProductService productService = new ProductService();
        private ClientTypeService clientTypeService = new ClientTypeService();

        #region 获取数据
        public async Task<TData<List<FunnelEntity>>> GetList(FunnelListParam param)
        {
            TData<List<FunnelEntity>> obj = new TData<List<FunnelEntity>>();
            obj.Result = await funnelService.GetList(param);
            obj.TotalCount = obj.Result.Count;
            obj.Tag = 1;
            return obj;
        }

        public async Task<TData<List<FunnelEntity>>> GetPageList(FunnelListParam param, Pagination pagination)
        {
            List<AreaEntity> list = await areaCache.GetList();
            List<ProductEntity> products = await productService.GetList(null);
            List<ClientTypeEntity> clientTypes = await clientTypeService.GetList(null);


            TData<List<FunnelEntity>> obj = new TData<List<FunnelEntity>>();
            obj.Result = await funnelService.GetPageList(param, pagination);
            obj.TotalCount = pagination.TotalCount;
            obj.Tag = 1;
            foreach (var item in obj.Result)
            {
                var strArea = string.Empty;
                var tempArea = item.AreaId.Split(',');
                foreach (var item_a in tempArea)
                {
                    strArea += list.FirstOrDefault(s => s.AreaCode == item_a)?.AreaName;
                }
                item.AreaId = strArea;
                item.ProductId = products.FirstOrDefault(s => s.Id?.ToString() == item.ProductId)?.ProductName;
                item.ClientType = clientTypes.FirstOrDefault(s => s.Id?.ToString() == item.ClientType)?.ClientTypeName;

            }
            return obj;
        }

        public async Task<TData<FunnelEntity>> GetEntity(long id)
        {
            TData<FunnelEntity> obj = new TData<FunnelEntity>();
            obj.Result = await funnelService.GetEntity(id);
            if (obj.Result != null)
            {
                //obj.Result.ProductName = obj.Result.ProductId.ToString();

                obj.Tag = 1;
            }
            return obj;
        }
        #endregion

        #region 提交数据
        public async Task<TData<string>> SaveForm(FunnelEntity entity)
        {
            TData<string> obj = new TData<string>();
            var id = entity?.ProductId;
            List<ProductEntity> products = await productService.GetList(null);
            var product = products?.FirstOrDefault(s => s.Id?.ToString() == id);
            entity.SumPrice = entity.ProductNumber * product.Price;
            await funnelService.SaveForm(entity);
            obj.Result = entity.Id.ParseToString();
            obj.Tag = 1;
            return obj;
        }

        public async Task<TData> DeleteForm(string ids)
        {
            TData obj = new TData();
            await funnelService.DeleteForm(ids);
            obj.Tag = 1;
            return obj;
        }

        public async Task<TData<SaleData>> GetBarData(string input)
        {
            TData<SaleData> obj = new TData<SaleData>();

            SaleData salemodeldata = new SaleData();
            List<Series> saleList = new List<Series>();
            int keyvalue = 0;
            if (string.IsNullOrEmpty(input))
            {
                keyvalue = DateTime.Now.Year;
            }
            else
            {
                var bl = int.TryParse(input, out keyvalue);
                if (!bl)
                {
                    keyvalue = DateTime.Now.Year;
                }
            }

            obj.Tag = 1;

            var query = await funnelService.GetList(null);
            query = query.Where(s => s.StatementTime.HasValue && s.StatementTime.Value.Year == keyvalue).ToList();

            var lst = await areaCache.GetList();
            var strlst = new List<string>();
            var strnamelst = new List<string>();
            foreach (var item in lst)
            {
                strlst.Add(item.Id.ToString());
                strnamelst.Add(item.AreaName);
            }
            var strname = strnamelst.ToList();
            var str = strlst.ToArray();

            for (int i = 1; i < 4; i++)
            {
                var partPrice = from r in query
                                where r.StatementTime < DateTime.Now && r.StatementTime > DateTime.Now.AddDays(-30 * i)
                                group r by r.AreaId.ToString() into g
                                select new { key = g.Key, value = g.Sum(s => Convert.ToDecimal(s.SumPrice)) };
                var sumPrice =
                               from m in str /*new string[] { "南区区域", "北区区域", "西区区域", "东区区域", "大客户", "其他" }*/
                               join x in partPrice.ToList() on m equals x.key into all
                               from k in all.DefaultIfEmpty()
                               select k == null ? 0 : k.value;

                var serie = new Series
                {
                    name = $"{i * 30}天",
                    data = sumPrice.ToList()
                };
                saleList.Add(serie);

            }
            //本年未结
            var partfPrice = from r in query
                             where r.Stage != "100%"
                             group r by r.AreaId.ToString() into g
                             select new { key = g.Key, value = g.Sum(s => Convert.ToDecimal(s.SumPrice)) };
            var sumfPrice =
                           from m in str/*new string[] { "南区区域", "北区区域", "西区区域", "东区区域", "大客户", "其他" }*/
                           join x in partfPrice.ToList() on m equals x.key into all
                           from k in all.DefaultIfEmpty()
                           select k == null ? 0 : k.value;

            var serief = new Series
            {
                name = "本年未结",
                data = sumfPrice.ToList()
            };
            saleList.Add(serief);
            //本年已结
            var parttPrice = from r in query
                             where r.Stage == "100%"
                             group r by r.AreaId.ToString() into g
                             select new { key = g.Key, value = g.Sum(s => Convert.ToDecimal(s.SumPrice)) };
            var sumtPrice =
                           from m in str /*new string[] { "南区区域", "北区区域", "西区区域", "东区区域", "大客户", "其他" }*/
                           join x in parttPrice.ToList() on m equals x.key into all
                           from k in all.DefaultIfEmpty()
                           select k == null ? 0 : k.value;

            var seriet = new Series
            {
                name = "本年已结",
                data = sumtPrice.ToList()
            };
            saleList.Add(seriet);
            saleList.ForEach(s => s.type = "bar");
            XAxis xAxis = new XAxis();
            xAxis.data = strname;
            salemodeldata.xAxis=xAxis;

            salemodeldata.series = saleList;
            obj.Result = salemodeldata;
            return obj;

        }

        public async Task<TData<Series>> GetPieData(string input)
        {

            TData<Series> obj = new TData<Series>();
            if (string.IsNullOrEmpty(input))
            {
                input = DateTime.Now.Year.ToString();
            }
            Series spd = new Series();
            int keyvalue = input.IsDateTime() ? DateTime.Now.Year : int.Parse(input);
            var query = await GetList(null);
            //.Where(s => s.StatementTime.Year == keyvalue);
            var lst =await clientTypeService.GetList(null);
            var strlst = new List<string>();
            foreach (var item in lst)
            {
                strlst.Add(item.Id.ToString());
            }
            var str = strlst.ToArray();
            var result = query.Result;
            var sum = result.Sum(s => Convert.ToDecimal(s.SumPrice.Value));
            var parttPrice = from r in result
                             group r by r.ClientType.ToString() into g
                             select new { key = g.Key, value = (g.Sum(s => Convert.ToDecimal(s.SumPrice)) * 100) / sum };
            var sumtPrice =
                               from m in str /*new string[] { "三级甲等", "三级乙等", "二级甲等", "二级以下", "军队医院", "民营医院", "口腔诊所", "其他" }*/
                               join x in parttPrice.ToList() on m equals x.key into all
                               from k in all.DefaultIfEmpty()
                               select new { key = m, value = (k == null ? 0 : k.value) };

            var typeList= await clientTypeService.GetList(null);
            var lstsum = sumtPrice.ToList();
            foreach (var item in lstsum)
            {
                var model = typeList.Where(s => s.Id.ToString().Equals(item.key)).FirstOrDefault();
                spd.dicts.Add(item.value, model.ClientTypeName);
            }
            obj.Result = spd;
            return obj;
        }

        #endregion

        #region 私有方法
        #endregion


    }
}


public class SaleData
{
    public XAxis xAxis { get; set; }
    public List<Series> series { get; set; }
}

public class XAxis
{
    public string type { get; set; } = "category";
    public List<string> data { get; set; } //= new List<string>();

}